import type { Directive } from 'vue'
import { ElMessage } from 'element-plus'

// 复制指令
export const copy: Directive = {
  mounted(el, binding) {
    el.addEventListener('click', () => {
      const text = binding.value || el.textContent
      
      if (navigator.clipboard) {
        // 使用现代API
        navigator.clipboard.writeText(text).then(() => {
          ElMessage.success('复制成功')
        }).catch(() => {
          fallbackCopyTextToClipboard(text)
        })
      } else {
        // 降级方案
        fallbackCopyTextToClipboard(text)
      }
    })
  }
}

// 降级复制方案
function fallbackCopyTextToClipboard(text: string) {
  const textArea = document.createElement('textarea')
  textArea.value = text
  
  // 避免滚动到底部
  textArea.style.top = '0'
  textArea.style.left = '0'
  textArea.style.position = 'fixed'
  textArea.style.opacity = '0'
  
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()
  
  try {
    const successful = document.execCommand('copy')
    if (successful) {
      ElMessage.success('复制成功')
    } else {
      ElMessage.error('复制失败')
    }
  } catch (err) {
    ElMessage.error('复制失败')
  }
  
  document.body.removeChild(textArea)
}
